// $Id: handler.c 58 2011-04-23 07:35:46Z cedric.shih@gmail.com $
/*
 * Copyright (C) 2011 Cedric Shih <cedric.shih@gmail.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

#include <stdlib.h>
#include <string.h>
#include <errno.h>

#include "log.h"

#include "handler.h"

struct niohandler_item *niohandler_new(const char *name,
		struct niohandler *ops, void *obj)
{
	struct niohandler_item *handler;

	niodebug("constructing");

	if (!(handler = calloc(1, sizeof(*handler)))) {
		nioerror("failed to calloc");
		goto exception;
	}

	if (!(handler->name = strdup(name))) {
		nioerror("failed to strdup: %s", strerror(errno));
		goto exception;
	}

	memcpy(&handler->ops, ops, sizeof(handler->ops));
	handler->obj = obj;

	return handler;

exception:
	niohandler_free(handler);
	return NULL;
}

void niohandler_free(struct niohandler_item *handler)
{
	niodebug("destructing: %p", handler);

	if (!handler) {
		return;
	}

//	niohandler_finalize(handler);

	if (handler->name) {
		free(handler->name);
	}

	if (handler->ops.free) {
		niodebug("invoking %p to free handler", handler->ops.free);

		(*handler->ops.free)(handler->obj);
	}

	free(handler);
}

int niohandler_setup(struct niohandler_item *handler)
{
	int rc;

	niodebug("setting up: %s", handler->name);

	if (handler->ops.setup) {
		niodebug("invoking %p to set up: %s",
				handler->ops.setup, handler->name);

		if ((rc = (*handler->ops.setup)(handler->obj,
				handler->name))) {
			nioerror("failed to set up: %s", strerror(rc));
			rc = NIO_EUNKNOWN;
			goto finally;
		}
	}

	rc = 0;

finally:
	return rc;
}

int niohandler_teardown(struct niohandler_item *handler)
{
	int rc;

	niodebug("tearing down: %s", handler->name);

	if (handler->ops.teardown) {
		niodebug("invoking %p to tear down: %s",
				handler->ops.teardown, handler->name);

		if ((rc = (*handler->ops.teardown)(handler->obj))) {
			nioerror("failed to tear down: %s", strerror(rc));
			rc = NIO_EUNKNOWN;
			goto finally;
		}
	}

	rc = 0;

finally:
	return rc;
}
